#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sqlite3, datetime, json
from django.shortcuts import render
from django.http import HttpResponse
from shared_resources import *

def index(request, special_request):
	initialize(request)
	
	output = ""
	
	header = version["icons"]["notifications"]+t("Your Notifications")
	
	if special_request == 'log-out/':
		log_out()
	error = ""
	if 'email' in request.POST.keys():
		log_in_result = log_in(request.POST["email"], request.POST["password"], 0)
		if log_in_result == 1:
			log_in_result = log_in(request.POST["email"], request.POST["password"], 1)
			if log_in_result == 1:
				error = '<p class="bg-warning">'+t('Wrong email and password combination. Press %s to reset your password.', (t('<a href="/users/reset-password/">'+t('here')+'</a>')))+'</p>'
		if log_in_result == 2:
			error = '<p class="bg-warning">'+t('Please %s in order to log in.', ('<a href="/users/verify-email/">'+t('verify your email')+'</a></p>'))
	
	# Get links after log in!
	output += error
	
	if not request.session["user"]["logged_in"]:
		
		header = version["icons"]["login"]+t("Log in")

		output += """
		<div class="col-xs-12">
        <div class="login-box">
        <form action="/users/" method="post">
        <table class="">
		<input class="login" type="text" name="email" placeholder="example@email.com"/>
		<input class="login" type="password" name="password" placeholder='"""+t('password')+"""'/>
		<input class="btn btn-primary" type="submit" value='"""+t('Log in')+"""'/>
		</table>
		</form>
        </div>
        </div>
		"""
	
	else:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    
		notifications = []
		
		if request.session["user"]["type"] == 0:
			if 'feedback' in request.POST.keys():
				did_homework = to_int(request.POST.get('did_homework', '0'))
				on_time = to_int(request.POST.get('on_time', '0'))
				# Check that we can actually post this feedback
				result = sql_cursor.execute("""select id from student_feedback where lesson_id = ? and student_id = ?""", (request.POST["lesson_id"], request.POST["student_id"])).fetchone()
				if result == None:
					sql_cursor.execute("""INSERT INTO student_feedback ('student_id', 'lesson_id', 'comment', 'on_time', 'did_homework', 'time') VALUES (?,?,?,?,?,?)""",(request.POST["student_id"], request.POST["lesson_id"], request.POST["feedback"], did_homework, on_time, time.time()))
					sql_connection.commit()
					
		if request.session["user"]["type"] == 1:
			if 'rating' in request.POST.keys() and int(request.POST["rating"]) != 0:
				# Check that we can actually post this feedback
				result = sql_cursor.execute("""select id from teacher_feedback where lesson_id = ? and student_id = ?""", (request.POST["lesson_id"], request.session["user"]["id"])).fetchone()
				if result == None:
					sql_cursor.execute("""INSERT INTO teacher_feedback ('student_id', 'lesson_id', 'rating', 'comment', 'time') VALUES (?,?,?,?,?)""",(request.session["user"]["id"], request.POST["lesson_id"], request.POST["rating"], request.POST["feedback"], time.time()))
					sql_connection.commit()
		
		if 'dismiss_type' in request.POST.keys():
			dismiss_type = int(request.POST["dismiss_type"])
			dismiss_id = int(request.POST["dismiss_id"])
			
			if dismiss_type == 0:
				sql_cursor.execute("""delete from notifications where id = ? and user_id = ? and user_type = ?""", (dismiss_id, request.session["user"]["id"], request.session["user"]["type"]))
			
			if dismiss_type == 1 and request.session["user"]["type"] == 1:
				sql_cursor.execute("""update students set schedule_changed = 0 where id = ?""", (request.session["user"]["id"],))
			sql_connection.commit()
			
		if request.session["user"]["type"] == 0:
			classes = []
			db_rows = sql_cursor.execute("""select id, subject from classes where teacher_id = ?""", (request.session["user"]["id"],))
			for class_id, subject in db_rows:
				classes.append({"id": class_id, "subject": subject, "students": []})
			
			for key, class_values in enumerate(classes):
				db_rows = sql_cursor.execute("""select student_id, (select first_name from students where id = student_id), (select middle_name from students where id = student_id), (select last_name from students where id = student_id) from student_classes where class_id = ?""", (class_values["id"],))
				for student_id, first_name, middle_name, last_name in db_rows:
					classes[key]["students"].append({"id": student_id, "name": display_name(first_name, middle_name, last_name)})
			
			for class_values in classes:
				for student_values in class_values["students"]:
					db_rows = sql_cursor.execute("""select id, start_time from lessons where confirmed = 1 and class_id = ? and start_time < ? and (select id from student_feedback where lesson_id = lessons.id and student_id = ?) is null""", (class_values["id"], time.time() - global_vars["timezone_offset"], student_values["id"]))
					for lesson_id, start_time in db_rows:
						notifications.append({
							"header": t("Student feedback needed"), 
							"text": t("Please comment on your lesson with %s in the %s"+
							' class you had on %s. This feedback will let the parents know about the students progress.', (student_values["name"], class_subjects[class_values["subject"]], '<a href="/office/staff-schedule/'+str(request.session["user"]["id"])+'/'+str(stamp_to_week(start_time))+'/">'+(stamp_to_display(start_time, "time_format"))+'</a>'))+
							('<form action="?" method="post"><div class="textareawrapper"><textarea name="feedback" style="width: 100%; height: 70px;" placeholder="'+t('How did the lesson go?')+'"></textarea></div>'
							'<table>'
							'<tr><td style="width: 100%; height: 30px;">'+t("On time:")+' </td><td><input name="on_time" type="checkbox" value="1" checked></td></tr>'
							'<tr><td style="width: 100%; height: 30px;">'+t("Did homework:")+' </td><td><input name="did_homework" type="checkbox" value="1" checked></td></tr>'
							'</table>'
							'<input type="hidden" name="lesson_id" value="'+str(lesson_id)+'">'
							'<input type="hidden" name="student_id" value="'+str(student_values["id"])+'">'
							'<div style="text-align: center;"><input type="submit" class="btn btn-primary" value="'+t('Send feedback')+'"></div>'
							'</form>'), 
							"dismiss_type": -1, 
							"dismiss_id": -1
						})
			
		if request.session["user"]["type"] == 1:
			result = sql_cursor.execute("""select schedule_changed from students where id = ?""", (request.session["user"]["id"], )).fetchone()
			if int(result[0]) == 1:
				notifications.append({"header": t("Schedule changed"), "text": t('Your schedule has changed. %s to view.', ('<a href="/office/student-schedule/'+str(request.session["user"]["id"])+'/">'+t('Click here')+'</a>')), "dismiss_type": 1, "dismiss_id": 0})
			
			classes = []
			db_rows = sql_cursor.execute("""select class_id, (select subject from classes where id = class_id), (select first_name from staff where id = (select teacher_id from classes where id = class_id)), (select middle_name from staff where id = (select teacher_id from classes where id = class_id)), (select last_name from staff where id = (select teacher_id from classes where id = class_id)) from student_classes where student_id = ?""", (request.session["user"]["id"],))
			for class_id, subject, first_name, middle_name, last_name in db_rows:
				classes.append({"id": class_id, "subject": subject, "teacher_name": display_name(first_name, middle_name, last_name)})
			
			for class_values in classes:
				db_rows = sql_cursor.execute("""select id, start_time from lessons where confirmed = 1 and class_id = ? and start_time < ? and (select id from teacher_feedback where lesson_id = lessons.id and student_id = ?) is null""", (class_values["id"], time.time(), request.session["user"]["id"]))
				for id, start_time in db_rows:
					notifications.append({
						"header": t("Feedback needed"), 
						"text": t("Please rate the performance of %s in the %s"+
						' lesson you had on %s. Your teacher will not see this feedback directly.', (class_values["teacher_name"], class_subjects[class_values["subject"]], '<a href="/office/student-schedule/'+str(request.session["user"]["id"])+'/'+str(stamp_to_week(start_time))+'/">'+(stamp_to_display(start_time, "time_format"))+'</a>'))+
						('<br /><div class="rating" id="'+str(id)+'_rating" value="0"></div>'
						'<form><input id="'+str(id)+'_rating_amount" type="hidden"> <div class="textareawrapper"><textarea id="'+str(id)+'_rating_feedback" style="width: 100%; height: 70px;" placeholder="'+t('What could be improved?')+'"></textarea></div></form>'
						'<div style="text-align: center;"><button class="btn btn-primary" type="submit" onclick="post_request({\'lesson_id\': '+str(id)+', \'rating\': $(\'#'+str(id)+'_rating_amount\').val(), \'feedback\': $(\'#'+str(id)+'_rating_feedback\').val()});">'+('Send feedback')+'</button></div>'
						'<script>update_stars("'+str(id)+'_rating", 0, "'+str(id)+'_rating_amount");</script>'), 
						"dismiss_type": -1, 
						"dismiss_id": -1
					})
			
		db_rows = sql_cursor.execute("""select id, subject, text from notifications where user_id = ? and user_type = ?""", (request.session["user"]["id"], request.session["user"]["type"]))
		for id, subject, text in db_rows:
			notifications.append({"header": subject, "text": text, "dismiss_type": 0, "dismiss_id": id})

		db_rows = sql_cursor.execute("""select lesson_id, (select start_time from lessons where id = lesson_id) from pending_confirmations where pending_confirmer_id = ? and pending_confirmer_type = ?""", (request.session["user"]["id"], request.session["user"]["type"]))
		for lesson_id, start_time in db_rows:
			if request.session["user"]["type"] == 0:
				notifications.append({"header": t("Lesson pending confirmation"), "text": t('Lesson starting on %s. %s to view.', (stamp_to_display(start_time, "date_time_format"), '<a href="/office/staff-schedule/'  +str(request.session["user"]["id"])+'/'+str(stamp_to_week(start_time))+'/">'+t('Click here')+'</a>')), "dismiss_type": -1, "dismiss_id": -1})
			elif request.session["user"]["type"] == 1:
				notifications.append({"header": t("Lesson pending confirmation"), "text": t('Lesson starting on %s. %s to view.', (stamp_to_display(start_time, "date_time_format"), '<a href="/office/student-schedule/'+str(request.session["user"]["id"])+'/'+str(stamp_to_week(start_time))+'/">'+t('Click here')+'</a>')), "dismiss_type": -1, "dismiss_id": -1})
		
		if len(notifications) == 0:
			output += t("You currently have no notifications.")
		if len(notifications) > 0:
			output += '<div class="row">'
		for notification in notifications:
			output += '<div class="col-xs-12 col-md-4"><div class="alert alert-warning alert-dismissible"><b>'+notification["header"]+'</b><br />'+notification["text"]+('<img class="notifcloser" src="/static/icons/schedule_confirm.png" onclick="post_request({\'dismiss_type\': '+str(notification["dismiss_type"])+', \'dismiss_id\': '+str(notification["dismiss_id"])+'});">' if notification["dismiss_type"] != -1 else "")+'</div></div>'
		if len(notifications) > 0:
			output += '</div>'
	
	return format_response(header, output)

def verify_email(request, token):
	initialize(request)
	output = ""
	
	sql_connection = sqlite3.connect(global_vars["database"])
	sql_cursor = sql_connection.cursor()

	if token != None:
		sql_cursor.execute("""update staff set email_token = null, email_verified = 1 where email_token = ?""", (token,))
		sql_cursor.execute("""update students set email_token = null, email_verified = 1 where email_token = ?""", (token,))
		sql_connection.commit()
		output += '<p class="bg-success">'+t('Your email address has been verified.')+'</p>'
	
	elif 'verification_email' in request.POST.keys():
		
		token = random_hex()[:8]

		sql_cursor.execute("""update staff set email_token = ? where email = ?""", (token, request.POST["verification_email"]))
		sql_cursor.execute("""update students set email_token = ? where email = ?""", (token, request.POST["verification_email"]))
		sql_connection.commit()
		
		if not send_email(request.POST["verification_email"], t(global_vars["mail_messages"]["verify_email"][0], (), True), t(global_vars["mail_messages"]["verify_email"][1], (global_vars["url"]+"/users/verify-email/"+token+"/"), True)):
			output += '<p class="bg-warning">'+t('Error sending email to user!')+'</p>'
		else:
			output += '<p class="bg-success">'+t('Verification email sent.')+'</p>'
	
	else:
		output += (
		'<form action="?" method="post">'
        '<table class="newuser table">'
		'<tr><td>'+t('Your email address:')+'</td><td><input type="text" name="verification_email"></td></tr>'
		'<tr><td></td><td><input class="btn btn-primary" type="submit" value="'+t('Send verification email')+'"></td></tr>'
		'</table>'
		'</form>'
		)
		
	return format_response(version["icons"]["email"]+t("Verify email"), output)
	
def reset_password(request, token):	
	initialize(request)
	output = ""
	
	sql_connection = sqlite3.connect(global_vars["database"])
	sql_cursor = sql_connection.cursor()    
		
	if token != None:
		password_updated = False
		if 'password_1' in request.POST.keys():
			if request.POST["password_1"] == request.POST["password_2"]:
				salt = random_hex()
				pass_hash = pass_derivation(request.POST["password_1"], salt)
				
				print pass_derivation(request.POST["password_1"], salt)
				print pass_derivation(request.POST["password_1"], salt)
				print pass_derivation(request.POST["password_1"], salt)

				sql_cursor.execute("""update staff set pass_hash = ?, pass_salt = ?, email_token = null where email_token = ?""", (pass_hash, salt, token))
				sql_cursor.execute("""update students set pass_hash = ?, pass_salt = ?, email_token = null where email_token = ?""", (pass_hash, salt, token))
				sql_connection.commit()
				output += '<p class="bg-success">'+t('Your password has been updated.')+'</p>'
				password_updated = True
			else:
				output += '<p class="bg-warning">'+t('Passwords did not match.')+'</p>'
		
		if not password_updated:
			output += (
			'<div class="col-xs-12 col-md-6 col-md-offset-3">'
			'<form action="?" method="post">'
			'<table class="newuser table">'
			'<tr><td>'+t('New password:')+'</td><td><input type="password" name="password_1"></td></tr>'
			'<tr><td>'+t('Retype new password:')+'</td><td><input type="password" name="password_2"><td></tr>'
			'<tr><td></td><td><input class="btn btn-primary" type="submit" value="'+('Reset password')+'"></td></tr>'
			'</table>'
			'</form></div>'
			)
	elif 'reset_email' in request.POST.keys():
		token = random_hex()[:8]

		sql_cursor.execute("""update staff set email_token = ? where email = ?""", (token, request.POST["reset_email"]))
		sql_cursor.execute("""update students set email_token = ? where email = ?""", (token, request.POST["reset_email"]))
		sql_connection.commit()
		
		if not send_email(request.POST["reset_email"], t(global_vars["mail_messages"]["reset_email"][0], (), True), t(global_vars["mail_messages"]["reset_email"][1], (global_vars["url"]+"/users/reset-password/"+token+"/"), True)):
			output += '<p class="bg-warning">'+t('Error sending email to user!')+'</p>'
		else:
			output += '<p class="bg-warning">'+t('Please check yor email to reset your password.')+'</p>'
		
	else:
		output += (
		'<div class="col-xs-12 col-md-6 col-md-offset-3">'
		'<p class="bg-info">'+t('This will send you an email about how to reset your password.')+'</p></br>'
		'<form action="?" method="post">'
		'<table class="newuser table">'
		'<tr><td>'+t('Enter your email address:')+'</td><td><input type="text" name="reset_email"></td></tr>'
		'<tr><td></td><td><input class="btn btn-primary" type="submit" value="'+t('Reset password')+'"></td></tr>'
		'</table>'
		'</form></div>'
		)
	
	return format_response(version["icons"]["login"]+t("Reset Password"), output)
